package com.sp.business.normalization.impl.mf2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TreeNode {
    private static final Logger logger = LoggerFactory
            .getLogger(TreeNode.class);

    private NodeType nodeType;
    private String text;
    private List<TreeNode> children;

    public TreeNode() {
    }

    public TreeNode(NodeType nodeType, String text) {
        this.nodeType = nodeType;
        this.text = text;
    }

    public NodeType getNodeType() {
        return nodeType;
    }

    public void setNodeType(NodeType nodeType) {
        this.nodeType = nodeType;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public List<TreeNode> getChildren() {
        if (children == null) {
            children = new ArrayList<TreeNode>();
        }
        return children;
    }

    public void setChildren(List<TreeNode> children) {
        this.children = children;
    }

    public List<TreeNode> getChildrenByType(NodeType nodeType) {
        List<TreeNode> nodes = new ArrayList<TreeNode>();
        for (TreeNode child : getChildren()) {
            if (child.getNodeType() == nodeType) {
                nodes.add(child);
            }
        }
        return nodes;
    }

    public TreeNode getChildByType(NodeType nodeType) {
        List<TreeNode> nodes = getChildrenByType(nodeType);
        if (nodes != null && nodes.size() > 1) {
            throw new RuntimeException("Single result expected: "
                    + nodeType.name());
        }

        TreeNode node = null;
        if (nodes.size() == 1) {
            node = nodes.get(0);
        }
        return node;
    }

    public Map<NodeType, String> getChildTextMap() {
        Map<NodeType, String> childMap = new HashMap<NodeType, String>();
        for (TreeNode child : children) {
            if (child.getChildren().size() == 0) {
                childMap.put(child.getNodeType(), child.getText());
            }
        }

        return childMap;
    }

    public static void printTree(TreeNode root, String indent) {
        logger.info(indent + root.getNodeType() + ":" + root.getText());
        for (TreeNode child : root.getChildren()) {
            printTree(child, indent + " ");
        }
    }
}
